<script lang="ts" setup>
defineOptions({
    name: 'BasePagination',
})
const emit = defineEmits(['update:modelValue'])
interface Props {
    modelValue: number
    totalPage: number
}
const props = withDefaults(defineProps<Props>(), {})
const inputEl = ref<HTMLInputElement | null>(null)
const inputValue = ref(props.modelValue)

function setModalValue(v: any) {
    let page = isNaN(Number(v)) ? 1 : v
    if (page > props.totalPage) {
        page = props.totalPage
    } else if (page < 1) {
        page = 1
    }
    emit('update:modelValue', page)
    if (inputEl.value)
        inputEl.value.value = page.toString()
}
const handleBlur = () => {
    setModalValue(inputValue.value)
}
// 处理回车键
const handleKeyUp = (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
        inputEl.value?.blur()
    }
}

watch(() => props.modelValue, (newVal) => {
    inputValue.value = newVal
})
</script>
<template>
    <div class="f-ull mt-4 flex center">
        <div class="flex items-center gap-x-[0.15rem] ">
            <BaseButton type="none" :disabled="modelValue === 1" @click="setModalValue(modelValue - 1)"
                class="pagination-button pagination-prev">
                <BaseIcon class="rotate-180" name="uni-arrow-right" />
            </BaseButton>
            <div class="pagination">
                <input ref="inputEl" size="2" type="number" v-model="inputValue" @blur="handleBlur" @keyup="handleKeyUp"
                    class="pagination-current" :min="1" :max="totalPage">
                <span class="text-[var(--color-text-white-2)] mx-[.125rem]">的</span>
                <div class="p-1 min-w-9 h-7 justify-center flex items-center">
                    <span>{{ totalPage }}</span>
                </div>
            </div>
            <BaseButton type="none" :disabled="modelValue === totalPage" @click="setModalValue(modelValue + 1)"
                class="pagination-button pagination-next">
                <BaseIcon name="uni-arrow-right" />
            </BaseButton>
        </div>
    </div>
</template>

<style scoped lang="scss">
.pagination {
    background-color: var(--color-bg-black-3);
    display: flex;
    align-items: center;
    border-radius: .125rem;
    padding: .25rem;
    font-size: .75rem;
    line-height: 1.125rem;
    font-weight: 700;
    color: var(--color-text-white-0);
}

.pagination-prev {
    border-radius: .5rem .125rem .125rem .5rem;
}

.pagination-button {
    background-color: var(--color-bg-black-3);
    height: 2.25rem;
    font-size: .875rem;
}

.pagination-next {
    border-radius: .125rem .5rem .5rem .125rem;
}

.pagination-current {
    background-color: var(--color-bg-black-5);
    height: 1.75rem;
    min-width: 2.25rem;
    border-radius: .25rem;
    padding: .5rem;
    text-align: center;
}
</style>
